package com.example.application4.activity;

import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuInflater;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.example.application4.R;
import com.example.application4.view.DrawView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

public class DrawActivity extends AppCompatActivity {
    private DrawView drawView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_draw);

        drawView = findViewById(R.id.draw_view);

        FloatingActionButton menuButton = findViewById(R.id.menu_button);
        menuButton.setOnClickListener(this::showMenu);
    }

    private void showMenu(android.view.View view) {
        // 创建 PopupMenu
        PopupMenu menu = new PopupMenu(this, view);
        MenuInflater menuInflater = menu.getMenuInflater(); // 获取菜单填充器
        menuInflater.inflate(R.menu.draw_menu, menu.getMenu()); // 填充菜单项
        menu.setOnMenuItemClickListener(item -> handleMenuItemClick(item.getItemId())); // 设置菜单项点击监听器
        menu.setGravity(Gravity.END); // 设置弹出菜单的位置
        menu.show(); // 显示弹出菜单
    }

    private boolean handleMenuItemClick(int itemId) {
        // 处理菜单项点击事件
        if (itemId == R.id.add) {
            handleAddAction();
            return true;
        } else if (itemId == R.id.save) {
            handleSaveAction();
            return true;
        } else if (itemId == R.id.delete) {
            handleDeleteAction();
            return true;
        } else {
            return false;
        }
    }

    private void handleSaveAction() {
        try {
            Toast.makeText(this, "保存", Toast.LENGTH_SHORT).show();
            boolean isSave = drawView.saveToPictures(this);
            if (isSave) {
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            Toast.makeText(this, "发生错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void handleAddAction() {
        try {
            Toast.makeText(this, "清屏", Toast.LENGTH_SHORT).show();
            drawView.reset(); // 调用 DrawView 的 reset 方法清空画布
        } catch (Exception e) {
            Toast.makeText(this, "发生错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void handleDeleteAction() {
        try {
            finish();
            Toast.makeText(this, "返回", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "发生错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}